package com.sgb.kjwl.view.ui.activity.manage;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.androidkun.xtablayout.XTabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityTradeHonorBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.manage.TradeHonorEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.adapter.manage.TradeHonorAdapter;
import com.sgb.kjwl.view.widget.EnterprisePopWindow;
import com.sgb.kjwl.view.widget.IpPopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.view.widget.manage.TheEnterpriseOfAreaPopWindow;
import com.sgb.kjwl.viewmodel.manage.TradeHonorModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * 行业荣誉
 */
public class TradeHonorActivity extends AppActivity implements TextView.OnEditorActionListener {
    @Inject
    TradeHonorModel viewModel;

    private ActivityTradeHonorBinding binding;
    TradeHonorAdapter tradeHonorAdapter;

    List<IpPickSelectEntity> mTradeCategoryData;//行业分类
    List<PickSelectEntity> mHonorCategoryData;//荣誉分类
    List<PickSelectEntity> mHonorTypeData;//荣誉类型
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> provinceData = new ArrayList<>();//省数据

    private IpPopWindow tradeTypeWindow;
    private TheEnterpriseOfAreaPopWindow honorCategoryWindow;
    private EnterprisePopWindow honorTypeWindow;
    private ThreeLevelAreaWindow cityPopWindow;//省市弹窗
    Map<String,Object> map;

    //省
    private String provinceNo = "";
    //地区
    private String mCityNo = "";

    //荣誉分类
    private String honorClassification = "";
    //荣誉类型
    private String honorLevelNo = "";

    private String name1 = "";
    private String name2 = "";
    private String name3 = "";

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
                .enterpriseManageModule(new EnterpriseManageModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, TradeHonorActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_trade_honor);
        binding.include.ivBack.setVisibility(View.VISIBLE);
        binding.include.ivBack.setOnClickListener(view -> finish());
        binding.include.editSearch.setHint("请输入荣誉荣耀名称");

        binding.include.tvSearch.setOnClickListener(this);
        binding.include.ivCancel.setOnClickListener(this);

        binding.tvCategory.setOnClickListener(this);
        binding.tvType.setOnClickListener(this);
        binding.tvPlace.setOnClickListener(this);
        binding.ivShowMore.setOnClickListener(this);
        binding.include.editSearch.setOnEditorActionListener(this);

        if (mTradeCategoryData == null || mTradeCategoryData.size() == 0) {
            viewModel.getTradeTypes();
        } else {
            setTablayout(mTradeCategoryData);
        }

        tradeHonorAdapter = new TradeHonorAdapter(this, null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setAdapter(tradeHonorAdapter);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getHonorList(false, map);
            }

            @Override
            public void onLoadMore() {
                viewModel.getHonorList(true, map);
            }
        });

        //荣誉分类
        honorCategoryWindow = new TheEnterpriseOfAreaPopWindow(getActivity());
        honorCategoryWindow.setBgView(binding.grayLayout);
        honorCategoryWindow.setTitleGone();
        honorCategoryWindow.setOnResultClick((key1, key2, key3) -> {
            name1 = (String) key2;
            boolean isProvince = (boolean) key3;
            if (isProvince) {
                honorClassification = (String) key1;
                honorLevelNo = "";
                map.put("honorClassification", honorClassification);
            } else {
                honorLevelNo = (String) key1;
            }
            //请求接口
            map.put("honorLevelNo", honorLevelNo);
            viewModel.getHonorList(false, map);

        });
        honorCategoryWindow.setOnDisMissClick(() -> {
            if (name1.equals("") || name1.equals("不限")) {
                binding.tvCategory.contentSelect(false, false);
            } else {
                binding.tvCategory.contentSelect(true, false);
            }
            if (honorClassification.equals("")) {
                binding.tvCategory.contentSelect(false, false);
            }
        });
        honorCategoryWindow.setiButtonClick(no -> setTypeDatas(honorCategoryWindow.getHonorType()));

        //荣誉类型
        honorTypeWindow = new EnterprisePopWindow(getActivity());
        honorTypeWindow.setBgView(binding.grayLayout);
        honorTypeWindow.setOnResultClick((key1, key2, key3) -> {
            name2 = (String) key2;
            //请求接口
            map.put("honorClassification", key1);
            viewModel.getHonorList(false, map);
        });
        honorTypeWindow.setOnDisMissClick(() -> {
            if (name2.equals("") || name2.equals("不限")) {
                binding.tvType.contentSelect(false, false);
            } else {
                binding.tvType.contentSelect(true, false);
            }
        });

        viewModel.getCityData();
        // 省 城市
        cityPopWindow = new ThreeLevelAreaWindow(getActivity()){
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                super.provinceClick(baseAreaEntity, position);
                if (!provinceNo.equals(baseAreaEntity.getId())){
                    mCityNo = "";
                    map.put("cityNo", mCityNo);
                }

                name3 = baseAreaEntity.getSimpleName();
                provinceNo = baseAreaEntity.getId();

                map.put("provinceNo", provinceNo);
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                super.cityClick(baseAreaEntity, position);
                mCityNo = baseAreaEntity.getId();

                name3 = baseAreaEntity.getSimpleName();
                map.put("cityNo", mCityNo);
            }

            @Override
            protected void reset() {
                super.reset();
                cityPopWindow.dismiss();
                viewModel.getHonorList(false, map);
            }
        };
        cityPopWindow.setBgView(binding.grayLayout);
        cityPopWindow.setThreeListIsGone(true);
        cityPopWindow.setCitySingle();
        cityPopWindow.setProvinceSingle();
        cityPopWindow.setOnResultClick((key1, key2, key3) -> {
            viewModel.getHonorList(false, map);
        });
        cityPopWindow.setOnDisMissClick(() -> {
            if (name3.equals("") || name3.equals("不限") && (!provinceNo.equals(""))) {
                binding.tvPlace.contentSelect(false, false);
            } else {
                binding.tvPlace.contentSelect(true, false);
            }
            if (provinceNo.equals("")) {
                binding.tvPlace.contentSelect(false, false);
            }
        });
    }

    @Override
    protected void init() {
        map = new HashMap<>();
        mTradeCategoryData = new ArrayList<>();
        mHonorCategoryData = new ArrayList<>();
        mHonorTypeData = new ArrayList<>();

        viewModel.getHonorList(false, map);
    }

    /**
     * 搜索框回调
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        closeKeybord();
        if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            String searchWord = binding.include.editSearch.getText().toString().trim();
            map.put("honorName", searchWord);
            viewModel.getHonorList(false, map);
        }
        return false;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.map_view:
                if (!ClickUtils.isDoubleClick()) {
                    TradeHonorSearchActivity.start(this);
                }
                break;
            case R.id.tv_search:
                String searchText = binding.include.editSearch.getText().toString().trim();
                map.put("honorName", searchText);
                viewModel.getHonorList(false, map);
                break;
            case R.id.tv_category:
                if (!ClickUtils.isDoubleClick()) {
                    binding.tvCategory.contentSelect(false, true);
                    if (mHonorCategoryData.size() == 0) {
                        viewModel.getHonorCategory();
                    } else {
                        showCategoryPopWindow();
                    }
                }
                break;
            case R.id.tv_type:
                if (!ClickUtils.isDoubleClick()) {
                    binding.tvType.contentSelect(false, true);
                    if (mHonorTypeData.size() == 0) {
                        viewModel.getHonorType();
                    } else {
                        showHonorTypePopWindow();
                    }
                }
                break;
            case R.id.tv_place:
                if (!ClickUtils.isDoubleClick()) {
                    binding.tvPlace.contentSelect(false, true);
                    if (provinceData.size() == 0) {
                        viewModel.getCityData();
                    } else {
                        showProvincePopWindow();
                    }

                }
                break;
            case R.id.iv_show_more:
                if (!ClickUtils.isDoubleClick()) {
                    if (mTradeCategoryData != null) {
                        showTradeTypePopWindow2(mTradeCategoryData);
                    }
                }
                break;
            case R.id.iv_cancel:
                if (!binding.include.editSearch.getText().toString().isEmpty()) {
                    binding.include.editSearch.setText("");
                    map.remove("honorName");
                    viewModel.getHonorList(false, map);
                }
                break;
        }
    }

    public void showList(List<TradeHonorEntity> list, boolean isLoadMore) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                binding.recyclerView.loadMoreComplete();
                tradeHonorAdapter.addDatas(list);
            } else {
                binding.recyclerView.setNoMore(true);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            binding.recyclerView.refreshComplete();
            if (null != list && list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                tradeHonorAdapter.setDatas(list);
                binding.recyclerView.setLoadingMoreEnabled(true);
            } else {
                tradeHonorAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }


    public void setTablayout(List<IpPickSelectEntity> datas) {
        mTradeCategoryData = datas;
        for (int i = 0; i < datas.size(); i++) {
            binding.tablayout.addTab(binding.tablayout.newTab().setText(datas.get(i).getName()));
        }
        binding.tablayout.setOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                map.put("industryTypeNo", mTradeCategoryData.get(tab.getPosition()).getValue());
                viewModel.getHonorList(false, map);
                tradeTypeWindow.setDefItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(XTabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(XTabLayout.Tab tab) {

            }
        });

        //行业分类
        tradeTypeWindow = new IpPopWindow(getActivity());
        tradeTypeWindow.setBgView(binding.grayLayout);
        tradeTypeWindow.setOnResultClick((type, key2, key3) -> {
            int index = mTradeCategoryData.indexOf(type);
            binding.tablayout.getTabAt(index).select();
        });
        tradeTypeWindow.setOnDismissListener(() -> binding.ivShowMore.setImageResource(R.mipmap.btn_expand1));
    }

    //行业分类
    public void showTradeTypePopWindow2(List<IpPickSelectEntity> datas) {
        tradeTypeWindow.setData(datas);
        tradeTypeWindow.showPopwindow(binding.tabLayout, 0, 0);
        binding.ivShowMore.setImageResource(R.mipmap.btn_expand_up_gray);

    }

    //设置荣誉分类数据
    public void setCategoryDatas(List<PickSelectEntity<List<PickSelectEntity>>> datas) {
        mHonorCategoryData.clear();
        mHonorCategoryData.addAll(datas);
        honorCategoryWindow.setData(mHonorCategoryData);
        honorCategoryWindow.showPopwindow(binding.roomLayout, 0, 0);
    }

    public void showCategoryPopWindow() {
        honorCategoryWindow.setData(mHonorCategoryData);
        honorCategoryWindow.showPopwindow(binding.roomLayout, 0, 0);
    }


    //设置荣誉类型数据
    public void setTypeDatas(List<PickSelectEntity> datas) {
        mHonorTypeData.clear();
        mHonorTypeData.addAll(datas);
        PickSelectEntity pickSelectEntity = new PickSelectEntity();
        pickSelectEntity.setProjectscale("不限");
        pickSelectEntity.setNo("");
        mHonorTypeData.add(0, pickSelectEntity);
        honorCategoryWindow.setCityDatas(mHonorTypeData);
    }

    public void showHonorTypePopWindow() {
        honorTypeWindow.setData(mHonorTypeData, false, false);
        honorTypeWindow.showPopwindow(binding.roomLayout, 0, 0);
    }

    private void showProvincePopWindow() {
        cityPopWindow.showPopwindow(binding.roomLayout, 0, 0);
    }

    public void setCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas, String areaCode) {
        provinceData = datas;
        cityPopWindow.setDataForCompany(datas, true);
    }

}
